package com.jeesite.modules.sys.wx.qy.util;

import sun.misc.BASE64Decoder;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class DloadImgUtil {
    /**
     * 根据内容类型判断文件扩展名
     *
     * @param contentType 内容类型
     * @return
     */
    public static String getFileexpandedName(String contentType) {
        String fileEndWitsh = "";
        if ("image/jpeg".equals(contentType))
            fileEndWitsh = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileEndWitsh = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileEndWitsh = ".amr";
        else if ("video/mp4".equals(contentType))
            fileEndWitsh = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileEndWitsh = ".mp4";
        return fileEndWitsh;
    }
    /**
     * 获取媒体文件
     * @param accessToken 接口访问凭证
     * @param mediaId 媒体文件id
     * @param savePath 文件在本地服务器上的存储路径
     * */
    public static String downloadMedia(String accessToken, String mediaId, String savePath, String filePath) {

        String returnPath = "";
        // 拼接请求地址
        String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);

        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");

            if (!savePath.endsWith("/")) {
                savePath += "/";
            }
            // 根据内容类型获取扩展名
            String fileExt = DloadImgUtil.getFileexpandedName(conn.getHeaderField("Content-Type"));

//          System.out.println("fileExt : " + fileExt);

            // 将mediaId作为文件名
            filePath = filePath + mediaId + fileExt;

            System.out.println("filePath:======" + filePath);
            System.out.println("savePath:======" + savePath);


            returnPath = "|" + savePath + mediaId + fileExt;
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            FileOutputStream fos = new FileOutputStream(new File(filePath));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();

            conn.disconnect();
            String info = String.format("下载媒体文件成功，filePath=" + filePath);
//            System.out.println(info);
        } catch (Exception e) {
            String error = String.format("下载媒体文件失败：%s", e);
            System.out.println(error);
        }
        return returnPath;
    }


    /**
     * 获取多张媒体文件
     * @param accessToken 接口访问凭证
     * @param savePath 文件在本地服务器上的存储路径
     * */
    public static String downloadMedias(String accessToken, String mediaIds, String savePath, String filePath) {

        String returnPath = "";
        String myurl = "";//用来存储
        String[] mediaId = mediaIds.split(",");
        for (int i = 0; i < mediaId.length; i++) {


        // 拼接请求地址
        String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId[i]);

        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");

            if (!savePath.endsWith("/")) {
                savePath += "/";
            }
            // 根据内容类型获取扩展名
            String fileExt = DloadImgUtil.getFileexpandedName(conn.getHeaderField("Content-Type"));

//          System.out.println("fileExt : " + fileExt);

            // 将mediaId作为文件名
            myurl = filePath + mediaId[i] + fileExt;

            System.out.println("filePath:======" + filePath);
            System.out.println("savePath:======" + savePath);

            String fileurl = "|" + savePath + mediaId[i] + fileExt;

            returnPath += fileurl;
            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            FileOutputStream fos = new FileOutputStream(new File(myurl));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();

            conn.disconnect();
            String info = String.format("下载媒体文件成功，filePath=" + myurl);
//            System.out.println(info);
        } catch (Exception e) {
            String error = String.format("下载媒体文件失败：%s", e);
            System.out.println(error);
        }
        }
        return returnPath;
    }

    public static String GenerateImage(String imgStr, String filePath, String savePath) {
        //对字节数组字符串进行Base64解码并生成图片
        String imgStr2 = imgStr.split(",")[1];
//                substring(2);//裁剪前缀"data:image/jpeg;base64,"
        if (imgStr2 == null) //图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        //使用UID作为文件名
        String uuidStr = UUID.randomUUID().toString();
        String myurl = "";//数据库存储图片地址
        filePath=filePath+uuidStr+".jpg"; //保存在文件管理器中的文件路径
        myurl="|" + savePath+uuidStr+".jpg";
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr2);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }


            //生成jpeg图片
            OutputStream out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            out.close();
            return myurl;
        }
        catch (Exception e)
        {
            return null;
        }
    }
}